/**
 * (created at 2011-1-19)
 */
package qiushuo.mysqlparser.ast.expression.primary;

import java.util.List;

import qiushuo.mysqlparser.ast.expression.Expression;
import qiushuo.mysqlparser.generator.SQLType;
import qiushuo.mysqlparser.util.Pair;

/**
 * <code>'CASE' ('WHEN' condition 'THEN' result)+ ('ELSE' result)? 'END' </code>
 * 
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public class CaseWhenOperatorExpression extends PrimaryExpression {
    final List<Pair<Expression, Expression>> whenList;
    final Expression elseResult;

    public CaseWhenOperatorExpression(List<Pair<Expression, Expression>> whenList, Expression elseResult) {
        this.whenList = whenList;
        this.elseResult = elseResult;
    }

    @Override
    public String generateSql(SQLType type) {
        switch (type) {
        case MySQL:
            StringBuilder sb = new StringBuilder();
            sb.append("CASE ");
            for (Pair<Expression, Expression> pair : whenList) {
                sb.append(" WHEN ").append(pair.getFirst()).append(" THEN ").append(pair.getSecond());
            }
            if (elseResult != null) {
                sb.append(" ELSE ").append(elseResult.generateSql(type));
            }
            sb.append(" END");
            return sb.toString();
        default:
            throw new UnsupportedOperationException("only mysql sql can be generated");
        }
    }

}
